﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using TSVNAddin.Config;

namespace TSVNAddin.TSVN
{
	public class TortoiseProcExecutor
	{
		private readonly ProcessStarter _ProcessStarter;
		private readonly ConfigStorage _ConfigStorage;

		public TortoiseProcExecutor(ProcessStarter processStarter, ConfigStorage configStorage)
		{
			_ProcessStarter = processStarter;
			_ConfigStorage = configStorage;
		}

		public virtual void Exec(TortoiseProcCommandType tortoiseCommandType)
		{
			string arguments = string.Format("/command:{0}", tortoiseCommandType);
			_ProcessStarter.Start(GetFileName(), arguments);
		}

		public virtual void Exec(TortoiseProcCommandType tortoiseCommandType, string path, params TortoiseProcArgumentType[] tortoiseArguments)
		{
			string strArgs = string.Empty;
			foreach (TortoiseProcArgumentType argumentType in tortoiseArguments)
				strArgs += string.Format(" /{0}", argumentType);

			string[] paths = GetPaths(tortoiseCommandType, path);

			foreach (string p in paths)
			{
				string arguments = string.Format("/command:{0} /path:\"{1}\"{2}", tortoiseCommandType.ToString().ToLower(), p, strArgs);
				_ProcessStarter.Start(GetFileName(), arguments);
			}
		}

		private string[] GetPaths(TortoiseProcCommandType tortoiseCommandType, string path)
		{
			if (tortoiseCommandType != TortoiseProcCommandType.Diff)
				return new string[] { path };

			return path.Split('*');
		}

		private string GetFileName()
		{
			return _ConfigStorage.LoadAddinConfig().ProcPath;
		}
	}
}
